<template>
    <div class="common-layout">
        <el-container>
            <el-main>
                <!-- 按钮组件 -->
                <div class="btn">
                    <div class="inp">
                        <el-input placeholder="请输入管理员名称" clearable v-model="input" />
                    </div>
                    <el-button type="primary" :icon="Search" @click="search">查找</el-button>
                    <el-button type="primary" :icon="Edit" @click="add">添加</el-button>
                </div>
                <!-- 表格组件 -->
                <div class="tab">
                    <el-table :data="adminData" style="width: 100%" border>
                        <el-table-column prop="id" label="管理员ID" />
                        <el-table-column prop="username" label="管理员名称" />
                        <el-table-column prop="realname" label="真实姓名" />
                        <el-table-column prop="phone" label="电话" />
                        <el-table-column prop="roleIds" label="管理员角色">
                            <template #default="scope">
                                <div v-for="item in scope.row.roleIds" class="tags">
                                    <el-tag>{{ getRoles(item) }}</el-tag>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="gmtCreate" label="操作">
                            <template #default="scope">
                                <el-button type="primary" @click="handleEdit(scope.row)">修改</el-button>
                                <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 添加+修改弹出框 -->
                <el-dialog v-model="dialogFormVisible" :title="bool == true ? '添加' : '修改'" style="width: 40vW;"
                    destroy-on-close>
                    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
                        class="demo-ruleForm">
                        <el-form-item label="用户名" prop="username">
                            <el-input v-model="ruleForm.username" :disabled="!bool" />
                        </el-form-item>
                        <el-form-item label="手机号" prop="phone">
                            <el-input v-model="ruleForm.phone" />
                        </el-form-item>
                        <el-form-item label="密码" prop="password" v-if="bool == true">
                            <el-input v-model="ruleForm.password" type="password" />
                        </el-form-item>
                        <el-form-item label="真实姓名" prop="realname">
                            <el-input v-model="ruleForm.realname" />
                        </el-form-item>
                        <el-form-item label="角色">
                            <el-select v-model="ruleForm.roleIds" multiple style="width: 240px">
                                <el-option v-for="item in PopoutData" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button type="primary" @click="submitForm(ruleFormRef)">
                                {{ bool == true ? '新增' : '修改' }}
                            </el-button>
                            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                        </span>
                    </template>
                </el-dialog>
                <!-- 分页组件 -->
                <Pagination @page-change="handlePagehange" v-bind="datas" />
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import type { admins, User, rls } from '@/type/params'//引入类型
import { ref, onMounted, reactive } from 'vue'//引入响应式，生命周期
import { Search, Edit } from '@element-plus/icons-vue'//引入图标
import { post } from '@/untils/request'//引入请求方式
import Pagination from '@/components/Pagination.vue' //引入分页组件
import { ElMessage } from 'element-plus'//引入消息提示框
import type { FormInstance } from 'element-plus'


const ruleFormRef = ref<FormInstance>()
const adminData = ref([])//管理员列表
let rolesData: rls[] = reactive([]) //枚举列表
let PopoutData: rls[] = reactive([])  //下拉框角色列表

const datas = ref<admins>({//渲染页面数据
    total: 0,//总条数
    page: 1,//当前页面
    limit: 10,//一页面所显示的条数
    username: '',//搜索框关键词
    _gp: 'admin',
    _mt: 'list',
})
const roles = {//角色枚举数据
    _gp: 'admin.role',
    _mt: 'options',
}
const dialogs = {//弹框数据
    _gp: 'admin.role',
    _mt: 'list',
}
const input = ref('')//搜索框
const dialogFormVisible = ref(false)//修改角色弹框，默认隐藏状态
const bool = ref(false)//bool标识进入添加/修改
const ruleForm = reactive({//表单数据
    username: '',//用户名
    realname: '',//真实姓名
    phone: '',//手机号
    roleIds: [],//角色id
    password: ''//密码
})
const clearForm = reactive({//清空后的表单数据
    ...ruleForm
})
//生命周期---挂载后
onMounted(() => {
    init()
})
//非空验证
const rules = reactive({
    username: [{ required: true, trigger: 'blur', message: "用户名不能为空" }],
    password: [{ required: true, trigger: 'blur', message: "密码不能为空" }],
    phone: [{ required: true, trigger: 'blur', message: "手机号不能为空" }, { required: true, trigger: 'blur', message: "手机号格式不正确", pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ }],
    realname: [{ required: true, trigger: 'blur', message: "真实姓名不能为空" }, { required: true, trigger: 'blur', message: "请输入汉字", pattern: /^[\u4e00-\u9fa5]+$/ }]
})
//渲染
function init() {
    post(datas.value).then(res => {//管理员
        let { items } = res.data
        let { data } = res
        adminData.value = items//赋值表格
        datas.value.total = data.total//赋值总条数
    }).catch(err => {
        console.log(err);
    })
    post(roles).then(res => {//角色枚举
        let { data } = res
        rolesData = data
    }).catch(err => {
        console.log(err);
    })
    post(dialogs).then(res => {//弹框角色管理
        let { items } = res.data
        PopoutData = items
    }).catch(err => {
        console.log(err);
    })
};
//搜索
function search() {
    datas.value.username = input.value //赋值给输入框
    init()//刷新
}
//分页
function handlePagehange(s: { page: number, limit: number }) {
    datas.value.page = s.page
    datas.value.limit = s.limit
    init()
}
//删除
function handleDelete(index: number, row: User) {
    console.log(index, row)
    const datasDlet = {//删除角色管理数据
        _gp: 'admin',
        _mt: 'delete',
        id: row.id,//将当前对象的id赋值给角色id(roleId)
    }
    //@ts-ignore
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    )
        .then(() => {
            post(datasDlet).then(res => {
                console.log(res);
                adminData.value.splice(index, 1)//点击确定进入请求，请求成功删除当前行
                ElMessage.success('删除成功')
            }).catch(err => {
                console.log(err);
                ElMessage.info('删除失败')
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//角色枚举
function getRoles(item: number) {
    for (let s of rolesData) {
        if (item == s.value) {
            return s.label
        }
    }
    return ''
}
//添加--显示弹出框
function add() {
    bool.value = true//bool为true进入添加
    dialogFormVisible.value = true//显示弹出框
    Object.assign(ruleForm, clearForm)//合并弹框弹框绑定的表单数据与表清空状态下的表单数据

}
//修改--显示弹出框
function handleEdit(row: User) {
    console.log(row)
    bool.value = false//bool为false进入修改
    dialogFormVisible.value = true//显示弹出框
    Object.assign(ruleForm, row)//Object.assign()方法用于合并表单+当前行---相当于给修改弹出框的数据进行了赋值操作
}
//修改确定按钮--请求对应数据
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            if (bool.value == true) {//bool为true请求添加的接口
                let adds = {
                    _gp: 'admin',
                    _mt: 'create',
                    adminDTO: JSON.stringify({//角色对象转json形式,并进行传值
                        ...ruleForm
                    })
                }
                post(adds).then(res => {
                    let { errno, errmsg } = res
                    if (200 == errno) {
                        ElMessage.success('添加成功')
                        dialogFormVisible.value = false//隐藏弹出框
                        init()//刷新
                    } else {
                        ElMessage.error(errmsg)
                    }

                }).catch(err => {
                    console.log(err);
                    ElMessage.info('添加失败')
                })

            } else if (bool.value == false) {//bool为false请求修改的接口
                let edits = {
                    _gp: 'admin',
                    _mt: 'edit',
                    adminDTO: JSON.stringify({//角色对象转json形式,并进行传值
                        ...ruleForm
                    })
                }
                post(edits).then(res => {
                    console.log(res, '修改的数据');
                    ElMessage.success('修改成功')
                    dialogFormVisible.value = false//隐藏弹出框
                    init()//刷新
                }).catch(err => {
                    console.log(err);
                    ElMessage.info('修改失败')
                })
            }

        } else {
            return false
        }
    })
}
//重置
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}
</script>
<style lang="less" scoped>
.el-container {
    font-size: 14px;

    .btn {
        width: 100%;
        display: flex;

        .inp {
            width: 200px;
            margin-right: 15px;
        }
    }

    .btn,
    .tab {
        margin-bottom: 20px;
    }

    .tab {
        .tags {
            display: flex;
            flex-wrap: wrap;
            width: 100%;
            align-items: center;
            margin: 5px 0px;
        }
    }

}
</style>
